<script setup lang="js">
import { ref,onMounted } from "vue";
import { useRouter } from "vue-router";
import {Search, Tickets} from "@element-plus/icons-vue";
import {fetchRoleList,createRole,updateRole,updateRoleStatus,deleteRole} from "@/api/roleList.js";
import {ElMessage, ElMessageBox} from "element-plus";

const router = useRouter();
const defaultListQuery = {
  pageNum: 1,
  pageSize: 5,
  keyword: null
};
const defaultRole = {
  id: null,
  name: null,
  description: null,
  adminCount: 0,
  status: 1
};
const listQuery = Object.assign({}, defaultListQuery);
const role = Object.assign({}, defaultRole);

const formData = ref({
  roleName: null
});
const total = ref(0);
const roleList = ref([]);

// 弹窗数据
const rolesVisible = ref(false);
const roleData = ref({
  id: null,
  name: null,
  description: null,
  adminCount: 0,
  status: 1
});
const isEdit = ref(false);

onMounted(() => {
    getRolesList();
});

const formatDate = (date) => {
  // 检查是否为 Date 对象
  if (!(date instanceof Date)) {
    date = new Date(date);
  }
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

const getRolesList = async () => {
  const res = await fetchRoleList(listQuery);
  roleList.value = res.data.data.list;
  total.value = res.data.data.total;
}

const handleSearch = () => {
  listQuery.pageNum = 1;
  listQuery.keyword = formData.value.roleName;
  getRolesList();
}

const handleResetSearch = () => {
  listQuery.pageNum = 1;
  listQuery.keyword = null;
  formData.value.roleName = null;
  getRolesList();
}

const handleAdd = () => {
  rolesVisible.value = true;
  isEdit.value = false;
  roleData.value = Object.assign({}, defaultRole);
}

const handleStatusChange = (row) => {
  ElMessageBox.confirm(`是否${row.status === 1? '启用' : '禁用'}角色${row.name}?`,'提示：',{
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    updateRoleStatus(row.id, {status: row.status}).then((res) => {
      ElMessage.warning(res.data.message);
      ElMessage.success(`${row.status === 1 ? '启用' : '禁用'}角色${row.name}成功`);
      getRolesList();
    });
  }).catch(() => {
    // 取消操作
    ElMessage.info('操作已取消');
    row.status = row.status === 1 ? 0 : 1;
  });
}

const handleSelectMenu = (row) => {
  router.push({ path: '/permission/allocMenu', query:{roleId:row.id} });
}

const handleSelectResource = (row) => {
  router.push({ path: '/permission/allocResource', query:{roleId:row.id} });
}

const handleUpdate = (row) => {
  rolesVisible.value = true;
  isEdit.value = true;
  roleData.value = Object.assign({}, row);
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`是否删除角色${row.name}?`,'提示：',{
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    let ids = [];
    ids.push(row.id);
    let params = new URLSearchParams();
    params.append('ids', ids);
    deleteRole(params).then((res) => {
      ElMessage.warning(res.data.message);
      ElMessage.success(`删除角色${row.name}成功`);
      getRolesList();
    });
  }).catch(() => {
    ElMessage.info('操作已取消');
  });
}

const handleDialogConfirm = () => {
  ElMessageBox.confirm('是否提交？', '提示：', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    if (isEdit.value) {
      updateRole(roleData.value.id, roleData.value).then((res) => {
        ElMessage.warning(res.data.message);
        ElMessage.success(`修改角色${roleData.value.name}成功`);
        rolesVisible.value = false;
        getRolesList();
      });
    } else {
      createRole(roleData.value).then((res) => {
        ElMessage.warning(res.data.message);
        ElMessage.success(`新增角色${roleData.value.name}成功`);
        rolesVisible.value = false;
        getRolesList();
      });
    }
  }).catch(() => {
    ElMessage.info('操作已取消');
  })
}

// TODO: 分页操作方法
const handleSizeChange = (size) => {
  listQuery.pageSize = size;
  getRolesList();
}
const handleCurrentChange = (val) => {
  listQuery.pageNum = val;
  getRolesList();
}

</script>

<template>
    <div class="role-list">
      <!-- 筛选列表 -->
      <div class="role-search">
        <div class="logo">
          <div class="logo-text">
            <el-icon>
              <Search/>
            </el-icon>
            <span>筛选搜索</span>
          </div>
          <div class="search-btn">
            <el-button type="primary" @click="handleSearch()">查询结果</el-button>
            <el-button icon="refresh" @click="handleResetSearch()">重置</el-button>
          </div>
        </div>
        <div class="search">
          <el-form :inline="true" ref="searchForm" v-model="formData" label-width="100px">
            <el-form-item label="输入搜索内容:">
              <el-input v-model="formData.roleName" placeholder="角色名称" clearable></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 添加按钮-->
      <div class="add-list">
        <div class="add-btn">
          <el-icon>
            <Tickets/>
          </el-icon>
          <span>数据列表</span>
        </div>
        <div class="add-btn">
          <el-button type="primary" icon="plus" @click="handleAdd()">添加</el-button>
        </div>
      </div>
      
      <!-- 数据列表 -->
      <div class="role-table">
        <el-table ref="roleTable"
                  :data="roleList"
                  style="width: 100%;" border>
          <el-table-column label="编号" width="100" align="center">
            <template #default={row}>{{row.id}}</template>
          </el-table-column>
          <el-table-column label="角色名称" align="center">
            <template #default={row}>{{row.name}}</template>
          </el-table-column>
          <el-table-column label="描述" align="center">
            <template #default={row}>{{row.description}}</template>
          </el-table-column>
          <el-table-column label="用户数" align="center">
            <template #default={row}>{{row.adminCount}}</template>
          </el-table-column>
          <el-table-column label="添加时间" align="center">
            <template #default={row}>{{formatDate(row.createTime)}}</template>
          </el-table-column>
          <el-table-column label="是否启用" align="center">
            <template #default={row}>
              <el-switch
                  @change="handleStatusChange(row)"
                  :active-value="1"
                  :inactive-value="0"
                  v-model="row.status">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="350" align="center">
            <template #default={row}>
                <el-button size="small"
                           type="text"
                           @click="handleSelectMenu(row)">分配菜单
                </el-button>
                <el-button size="small"
                           type="text"
                           @click="handleSelectResource(row)">分配资源
                </el-button>
                <el-button size="small"
                           type="primary"
                           icon="edit"
                           @click="handleUpdate(row)">编辑
                </el-button>
                <el-button size="small"
                           type="danger"
                           icon="delete"
                           @click="handleDelete(row)">删除
                </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="page-bar">
        <el-pagination
            background
            layout="total, sizes,prev, pager, next,jumper"
            :total="total"
            :page-sizes="[5,10,15,20]"
            v-model:page-size="listQuery.pageSize"
            v-model:current-page="listQuery.pageNum"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>

    <!--  弹窗-->
  <el-dialog :title="isEdit ? '编辑角色:' : '新增角色:'"
             v-model="rolesVisible"
             width="30%"
  >
    <el-form :model="roleData"
             ref="roleForm"
             label-width="150px" size="small">
      <el-form-item label="角色名称：">
        <el-input v-model="roleData.name" style="width: 250px"></el-input>
      </el-form-item>
      <el-form-item label="角色描述：">
        <el-input v-model="roleData.description"
                  type="textarea"
                  :rows="5"
                  style="width: 250px"></el-input>
      </el-form-item>
      <el-form-item label="是否启用：">
        <el-radio-group v-model="roleData.status">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleDialogConfirm()">保存</el-button>
        <el-button @click="rolesVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

</template>

<style scoped lang="scss">
.role-list {
  margin-top: 20px;
  display: flex;
  flex-direction: column;

  .role-search {
    //height: 100px;
    padding: 20px;
    margin-bottom: 20px;
    border: 1px solid #d5d5d5;
    border-radius: 5px;
    background-color: #ffffff;
    display: flex;
    flex-direction: column;

    .logo {
      width: 100%;
      font-size: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      span {
        margin: 0 8px;
      }

      .search-btn {
        margin-left: 30px;
        padding: 0 10px;
      }
    }

    .search {
      width: 100%;

      .el-form {
        margin: 20px;

        .el-form-item {
          width: 280px;
        }
      }
    }
  }

  .add-list {
    //height: 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px 20px;
    margin-bottom: 20px;
    border: 1px solid #d5d5d5;
    border-radius: 5px;

    .add-btn {
      display: flex;
      align-items: center;

      span {
        margin-left: 8px;
        font-size: 18px;
      }
    }
  }

  .page-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20px 0;

  }
}
</style>